import sys
from PySide6.QtWidgets import QApplication, QMessageBox, QWidget
from PySide6.QtCore import QThread, Signal, Qt,QTimer
from PySide6.QtGui import QPixmap
from PySide6.QtMultimedia import QSoundEffect
import random
import time
import math

# region popup
class PopupThread(QThread):
    show_popup = Signal(str, str,str)
    close_popup = Signal()
    def __init__(self, parent=None):
        super().__init__(parent)
        self.What_I_want_to_say = [
            "降温了，你的外套够暖吗？","看你最近有点疲惫，是有什么烦心事吗？\n我都在",
            "知道你忙，但也要记得按时吃饭呀","累的时候，允许自己当个小孩，歇一歇吧",
            "你喜欢的那个口味，我刚好路过，给你带了一份","小小休息是为了更好的出发\n继续加油吧",
            "身体是革命的本钱\n照顾好自己比啥都重要","雨天慢行，带伞了吗？\n别让雨水淋湿了你的心情",
            "把疲惫留给昨天吧，轻松迎接夜晚的宁静","心里事儿太多就说出来嘛\n我一直在这里倾听你的心声",
            "寒冷冬日，有你真暖和，感谢一路陪伴和支持","平凡的日子也要闪闪发光\n每一天都值得被认真对待",
            "虽然距离遥远但心意相通\n想你的时候空气都是甜的","这些天辛苦了","有没有要帮忙的？",
            "别怕，慢慢来\n我就在旁边","你已经做得很好了\n别太苛责自己",
            "这件事确实不容易，换成是我也会觉得难","无论结果如何\n你都不是一个人面对",
            "我们一起想想办法？\n或许能换个角度看看","这次没达到预期\n但你积累的经验特别宝贵",
            "压力大的时候\n记得你背后还有我们","照顾别人的时候\n也别忘了心疼自己",
            "只要今天比昨天强就好！","别怕，你肯定能行！","只要努力，下次就一定能考好",
            "尽管很难，但你一直没有放弃","你做事情的态度非常不错！",
            "你一点都不怕困难，太难得了！","没关系，一切都会好起来的！"
        ]

        self.color = [
            "#FFB6C1","#FFFFC3","#87CEFA","#AFEEEE", 
            "#FFC0CB","#ADD8E6","#CBFFFF","#FFDAB9", 
            "#FFA07A","#C9C9FF","#FF8295","#FE9DAB"  
        ]
        self.dialog_num = 0

    def set_dialog_num(self, num):
        self.dialog_num = num

    def run(self):
        while self.dialog_num>0:
            self.dialog_num -= 1
            message = self.What_I_want_to_say[random.randint(0, len(self.What_I_want_to_say)-1)]
            color = self.color[random.randint(0, len(self.color)-1)]
            self.show_popup.emit("xxx", message,color)   

            time.sleep(0.03)
        self.close_popup.emit()

class SoundThread(QThread):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.sound = QSoundEffect()
        # self.sound.setSource(QUrl.fromLocalFile("sound.wav"))

    def run(self):
        self.sound.play()
        while self.sound.isPlaying():
            time.sleep(0.03)


# region care
class CareDialog(QWidget):
    def __init__(self):
        super().__init__()
        self.popup_init()

    def popup_init(self):
        self.dialog_num= 200
        self.msg_list = []
        self.popup_thread = PopupThread()
        self.popup_thread.set_dialog_num(self.dialog_num)
        self.popup_thread.show_popup.connect(self.show_popup)
        self.popup_thread.close_popup.connect(self.close_dialog)
        
        # 创建网格列表，将桌面平均分成150份
        self.available_grid_positions = self._create_screen_grid(self.dialog_num)
        
        self.popup_thread.start()
        
    def _create_screen_grid(self, grid_count):
        """将屏幕平均分成指定数量的网格，并返回所有网格的中心点坐标"""
        screen = QApplication.primaryScreen()
        screen_geometry = screen.size()
        screen_width = screen_geometry.width()
        screen_height = screen_geometry.height()
        
        # 计算网格的行列数（尽量接近正方形）
        grid_cols = int(grid_count ** 0.5)
        grid_rows = (grid_count + grid_cols - 1) // grid_cols
        
        # 计算每个网格的实际大小
        grid_width = screen_width // grid_cols
        grid_height = screen_height // grid_rows
        
        grid_positions = []
        
        # 计算所有网格的中心点坐标
        for row in range(grid_rows):
            for col in range(grid_cols):
                if len(grid_positions) >= grid_count:
                    break
                
                # 计算网格中心点坐标
                center_x = col * grid_width + grid_width // 2
                center_y = row * grid_height + grid_height // 2
                
                grid_positions.append((center_x, center_y))
            
        return grid_positions

    def show_popup(self, title, message, color="#fc65b8"):
        msg = QMessageBox(self)
        self.msg_list.append(msg)
        
        msg.setStyleSheet(f"""
            QMessageBox {{ 
                background-color: {color}; 
                font-size: 18px; 
            }}
            QMessageBox QLabel {{ 
                font-size: 18px; 
            }}

        """)
        # 禁用声音：设置自定义透明图标
        transparent_pixmap = QPixmap(1, 1)
        transparent_pixmap.fill(Qt.transparent)
        msg.setIconPixmap(transparent_pixmap)  
        
        msg.setText(message)
        msg.setWindowTitle(title)
        
        msg.setStandardButtons(QMessageBox.StandardButton.NoButton)  # 清除默认按钮
        
        # 设置为非模态，允许点击外部关闭
        msg.setWindowModality(Qt.NonModal)

        # 从可用网格位置中随机选择一个且不重复
        if self.available_grid_positions:
            # 随机选择一个网格位置
            center_x, center_y = random.choice(self.available_grid_positions)
            # 从列表中移除该位置，确保不重复
            self.available_grid_positions.remove((center_x, center_y))
            
            # 获取弹窗的推荐大小
            suggested_size = msg.sizeHint()
            msg_width = suggested_size.width()
            msg_height = suggested_size.height()

            # 计算弹窗左上角坐标，使其居中于网格中心点
            x = max(0, center_x - msg_width // 2)
            y = max(0, center_y - msg_height // 2 )

            
            # 确保弹窗不超出屏幕边界
            screen = QApplication.primaryScreen()
            screen_geometry = screen.size()
            x = min(x, screen_geometry.width() - msg_width)
            y = min(y, screen_geometry.height() - msg_height)
            
            msg.move(x, y)
        
        msg.show() 

    def close_dialog(self):
        # 如果弹窗数量不足以形成爱心形状，直接关闭
        if len(self.msg_list) < 10:
            for msg in reversed(self.msg_list[:]):
                msg.hide()
                time.sleep(0.01)
            return
        
        for msg in reversed(self.msg_list[:]):
            msg.setStyleSheet(f"""
            QMessageBox {{
                background-color: #fc65b8;
            }}
        """)
        QApplication.processEvents()

        # 清空文字、固定大小，并排列成爱心形状
        self._arrange_hearts_shape()
        
        # 延迟一段时间显示爱心形状后关闭
        QTimer.singleShot(2000, self._close_all_messages)

    def _arrange_hearts_shape(self):
        """将弹窗排列成爱心形状 - 优化版：增大爱心、增加弹窗、提升性能"""
        screen = QApplication.primaryScreen()
        screen_geometry = screen.size()
        screen_width = screen_geometry.width()
        screen_height = screen_geometry.height()
        
        # 动态设置弹窗数量和大小：基于屏幕分辨率调整
        popup_width, popup_height = 80, 80  # 可调整为80x80以增大弹窗
        max_points = min(len(self.msg_list), 200)  # 增加弹窗数量上限至500
        num_points = min(max_points, 200)  # 确保不超过合理上限
        
        # 预计算心形点：移出循环，提升性能
        heart_points = []
        for i in range(num_points):
            t = 2 * math.pi * i / num_points
            x_eq = 16 * (math.sin(t) ** 3)
            y_eq = 13 * math.cos(t) - 5 * math.cos(2*t) - 2 * math.cos(3*t) - math.cos(4*t)
            heart_points.append((x_eq, y_eq))
        
        # 计算爱心中心点和缩放因子（增大爱心尺寸）
        center_x = screen_width // 2
        center_y = screen_height // 2
        if heart_points:
            x_vals = [point[0] for point in heart_points]
            y_vals = [point[1] for point in heart_points]
            max_x = max(abs(val) for val in x_vals)
            max_y = max(abs(val) for val in y_vals)
            # 增大缩放比例：使用屏幕的85%而非60%，使爱心更大
            scale_x = (screen_width * 0.85) / (max_x * 2) if max_x > 0 else 100
            scale_y = (screen_height * 0.85) / (max_y * 2) if max_y > 0 else 100
            scale = min(scale_x, scale_y)
        else:
            scale = 100  # 默认值提高以增大爱心
        for msg in self.msg_list:
            msg.setText("")
            msg.setFixedSize(popup_width, popup_height)
            point_x, point_y = heart_points[0]
            x = center_x + point_x * scale - popup_width // 2
            y = center_y - point_y * scale - popup_height // 2
            x = max(0, min(x, screen_width - popup_width))
            y = max(0, min(y, screen_height - popup_height))
            
            msg.move(int(x), int(y))

        # 排列弹窗
        for i, msg in enumerate(self.msg_list):
            if i < len(heart_points):
                # 计算位置（翻转y轴）
                point_x, point_y = heart_points[i]
                x = center_x + point_x * scale - popup_width // 2
                y = center_y - point_y * scale - popup_height // 2
                x = max(0, min(x, screen_width - popup_width))
                y = max(0, min(y, screen_height - popup_height))
                
                msg.move(int(x), int(y))
                msg.show()
            else:
                msg.hide()  # 隐藏多余弹窗

    def _close_all_messages(self):
        """关闭所有弹窗"""
        for msg in reversed(self.msg_list[:]):
            msg.hide()
            time.sleep(0.01)
        
        # 清空列表
        self.msg_list.clear()
        QApplication.processEvents()
        self.show()
        self.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CareDialog()
    # window.show()

    sys.exit(app.exec())